/**
 * @describe cos图片上传
 * @author 游金宇(KM)
 * @date 2023-01-30 11:30:03
 */
import { cat } from '@shimotsuki/core';
import COS from 'cos-js-sdk-v5';



// cos资源上传

export interface CosUploadParams extends COS.Credentials {
    Path: string;
    Region: string;
    Bucket: string;
}

export interface Credentials {
    sessionToken: string;
    tmpSecretId: string;
    tmpSecretKey: string;
}

export interface ResUpload {
    credentials: Credentials;
    expiration: string;
    expiredTime: number;
    path: string;
    startTime: number;
}

function createCos(config: CosUploadParams) {
    return new COS({
        getAuthorization: (options, callback) => {
            callback(config);
        },
    });
}

export const upload = async (blob: Blob, name: string): Promise<string> => {
    return new Promise<string>(async (resolve, reject) => {
        const data = await cat.api.cos.getCosUploadParams();
        const cos = createCos({
            TmpSecretId: data.credentials.tmpSecretId,
            TmpSecretKey: data.credentials.tmpSecretKey,
            XCosSecurityToken: data.credentials.sessionToken,
            StartTime: data.startTime,
            ExpiredTime: data.expiredTime,
            Bucket: cat.env.bucket,
            Region: cat.env.region,
            Path: data.path,
        });
        // 需要转为Blob上传
        cos.putObject(
            {
                Bucket: cat.env.bucket,
                Region: cat.env.region,
                Key: `/${data.path}/meta/postcards/${name}.png`,
                Body: blob,
            },
            (err, data) => {
                if (err) {
                    reject(err);
                } else {
                    let res = data.Location;
                    resolve(res);
                }
            }
        );
    });
}

